package com.hup.utils.swing.customView.viewTable;

import lombok.Getter;

import javax.swing.*;
import javax.swing.plaf.basic.BasicTableHeaderUI;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

/**
 * @author hugan
 * @date 2019/9/15
 */
public class SummaryRowHeaderUI extends BasicTableHeaderUI {

    private final JTable table;
    @Getter
    private String[] tableHead;
    private String[] summaryHead;

    protected static SummaryRowHeaderUI initTable(JTable table, String[] tableHead) {
        SummaryRowHeaderUI headerUI = new SummaryRowHeaderUI(table, tableHead);
        JTableHeader tableHeader = table.getTableHeader();
        tableHeader.setUI(headerUI);
        //只用html靠右是不够的,还要让Label靠右
        DefaultTableCellRenderer defaultRenderer = (DefaultTableCellRenderer) tableHeader.getDefaultRenderer();
        defaultRenderer.setHorizontalAlignment(JLabel.TRAILING);
        return headerUI;
    }

    private SummaryRowHeaderUI(JTable table, String[] tableHead) {
        this.table = table;
        this.tableHead = tableHead;
        this.summaryHead = new String[tableHead.length];
    }

    protected void updateTableHead(String[] tableHead) {
        this.tableHead = tableHead;
        this.summaryHead = new String[tableHead.length];
        ((DefaultTableModel) table.getModel()).setColumnIdentifiers(tableHead);
        //不需要设置setPreferredSize,否则反而有显示bug
    }

    protected void setSummaryData(Object[] summary) {
        if (summary == null) {
            updateTableHead(tableHead);
            return;
        }

        /*
         * 表头换行的另一种方案:extends JTextArea implements TableCellRenderer
         * https://www.iteye.com/blog/weibaojun-524507
         * 表头颜色
         * https://blog.csdn.net/ygl19920119/article/details/78432774
         */

        int i = 0;
        int length = summary.length;
        for (String col : tableHead) {
            Object val = i < length ? summary[i] : null;
            if (val == null) {
                val = "　";
            }
            //要使用html属性实现靠右
            summaryHead[i] = "<html>"
                    + "<p align='right'>"
                    + col + "<br/>"
                    + val + ""
                    + "</p>"
                    + "</html>";
            i++;
        }
        //log.info("summaryHead={}", Arrays.toString(summaryHead));
        ((DefaultTableModel)table.getModel()).setColumnIdentifiers(summaryHead);
        //不需要设置setPreferredSize,否则反而有显示bug
    }

}
